import React from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import { MapView, Marker, MapType } from 'react-native-amap3d';
import { useRef, useEffect } from 'react';
import { COLORS } from '../styles/constants';

/**
 * MapAttractions 仅负责渲染地图与景点标记
 * props:
 * - region: 地图区域
 * - attractions: 景点数组
 * - onPressMarker: 点击标记事件
 */
// 自定义标记组件
function CustomMarker({ attraction }) {
  return (
    <View style={styles.customMarker}>
      <View style={styles.markerContainer}>
        <View style={styles.pinContainer}>
          <View style={styles.pin} />
        </View>
        <View style={styles.attractionInfo}>
          <Image
            source={{ uri: attraction.image }}
            style={styles.attractionImage}
          />
          <Text style={styles.attractionName} numberOfLines={1}>
            {attraction.name}
          </Text>
        </View>
      </View>
    </View>
  );
}

export default function MapAttractions({
  region: _region,
  attractions,
  onPressMarker,
}) {
  const mapRef = useRef(null);

  // 调试日志已移除，避免在部分设备触发空错误弹窗

  // 当景点数据变化时，自动调整地图视野到合适的范围
  useEffect(() => {
    if (!mapRef.current || !attractions || attractions.length === 0) return;

    // 延迟以等待地图渲染
    const timer = setTimeout(() => {
      try {
        const points = attractions.map(a => ({
          latitude: a.latitude,
          longitude: a.longitude,
        }));

        // 计算所有景点的边界
        const lats = points.map(p => p.latitude);
        const lngs = points.map(p => p.longitude);
        const minLat = Math.min(...lats);
        const maxLat = Math.max(...lats);
        const minLng = Math.min(...lngs);
        const maxLng = Math.max(...lngs);

        // 计算中心点
        const center = {
          latitude: (minLat + maxLat) / 2,
          longitude: (minLng + maxLng) / 2,
        };

        // 计算合适的缩放范围，确保所有景点都在视野内
        const latSpan = maxLat - minLat;
        const lngSpan = maxLng - minLng;
        const maxSpan = Math.max(latSpan, lngSpan);

        // 根据景点分布调整缩放级别，确保显示城市范围
        let latitudeDelta = 0.02; // 默认城市范围
        let longitudeDelta = 0.02;

        if (maxSpan > 0.01) {
          // 如果景点分布较广，适当扩大视野
          latitudeDelta = Math.max(0.02, maxSpan * 1.5);
          longitudeDelta = Math.max(0.02, maxSpan * 1.5);
        }

        // 使用 moveCamera 平滑移动到新位置（react-native-amap3d API）
        if (mapRef.current.moveCamera) {
          // 简单根据跨度估算一个缩放级别（AMap 3D 大致 3-20）
          const span = Math.max(latitudeDelta, longitudeDelta);
          let zoom = 12;
          if (span > 1) zoom = 6;
          else if (span > 0.5) zoom = 8;
          else if (span > 0.2) zoom = 10;
          else if (span > 0.05) zoom = 12;
          else if (span > 0.02) zoom = 14;
          else zoom = 16;

          mapRef.current.moveCamera({ target: center, zoom }, 1000);
        }
      } catch (error) {
        // 忽略非致命异常，但记录日志以便调试
      }
    }, 500); // 增加延迟时间确保地图完全加载

    return () => clearTimeout(timer);
  }, [attractions]);

  return (
    <View style={styles.mapContainer}>
      <MapView
        ref={mapRef}
        style={styles.map}
        initialCameraPosition={{
          target: { latitude: _region.latitude, longitude: _region.longitude },
          zoom: 12,
        }}
        myLocationEnabled={false}
        myLocationButtonEnabled={false}
        zoomGesturesEnabled={true}
        scrollGesturesEnabled={true}
        rotateGesturesEnabled={false}
        tiltGesturesEnabled={false}
        mapType={MapType.Standard}
        minZoom={8}
        maxZoom={18}
        onCameraIdle={() => {}}
        onLoad={() => {}}
        // 关键：限制地图只响应地图区域内的触摸
        onTouchStart={e => {
          // 让触摸事件只在地图区域内生效
          e.stopPropagation();
        }}
      >
        {attractions &&
          attractions.map(attraction => {
            return (
              <Marker
                key={attraction.id}
                coordinate={{
                  latitude: attraction.latitude,
                  longitude: attraction.longitude,
                }}
                title={attraction.name}
                description={`📍 ${attraction.address}\n⭐ 评分: ${attraction.rating} | 📏 距离: ${attraction.distance}`}
                onPress={() => {
                  onPressMarker?.(attraction);
                }}
              >
                <CustomMarker attraction={attraction} />
              </Marker>
            );
          })}
      </MapView>
    </View>
  );
}

const styles = StyleSheet.create({
  mapContainer: {
    width: '100%',
    height: 250,
  },
  map: {
    width: '100%',
    height: 250,
  },
  // 自定义标记样式
  customMarker: {
    alignItems: 'flex-start',
    justifyContent: 'center',
  },
  markerContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-start',
  },
  // 针形标注样式
  pinContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 8,
  },
  pin: {
    width: 0,
    height: 0,
    borderLeftWidth: 8,
    borderRightWidth: 8,
    borderBottomWidth: 16,
    borderLeftColor: 'transparent',
    borderRightColor: 'transparent',
    borderBottomColor: COLORS.primary,
    marginBottom: 2,
  },
  // 景点信息样式
  attractionInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: COLORS.background.card,
    borderRadius: 20,
    paddingHorizontal: 8,
    paddingVertical: 4,
    shadowColor: COLORS.shadow,
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
    elevation: 2,
  },
  attractionImage: {
    width: 30,
    height: 30,
    borderRadius: 15,
    marginRight: 6,
  },
  attractionName: {
    fontSize: 12,
    fontWeight: '600',
    color: COLORS.text.primary,
    maxWidth: 100,
  },
});
